// ./pages/HomePage.js
import React, { useState, useEffect, useContext  } from 'react';
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree,InputNumber    } from 'antd';
import { addMenu, delMenu, getMenu, listMenu, updateMenu } from "../../../api/system/menu";
import { DictContext } from '../../../context/context';
import SvgIcon  from '../../../components/svgIcon/index'
import { SearchOutlined , RedoOutlined, PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import DictTag from '../../../components/DictTag';
import IconSelect from '../../../components/IconSelect';
function Menu() {
      const { useDict, addDateRange, handleTree } = useContext(DictContext);
      const { sys_normal_disable } = useDict('sys_normal_disable');
    const [menuOptions, setMenuOptions] = useState([]);
    const [menuList, setMenuList] = useState([]);
    const [single, setSingle] = useState(true);
    const [multiple, setMultiple] = useState(true);
    const [formAdd] = Form.useForm();
    const [searchForm] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [open, setOpen] = useState(false);
    const [title, setTitle] = useState('');
    const [menuType, setMenuType] = useState('M');
    const [queryParams, setQueryParams] = useState({})

    // const menuType = [
    //     {
    //         value: 'M',
    //         label: '目录',
    //     },
    //     {
    //         value: 'C',
    //         label: '菜单',
    //     },
    //     {
    //         value: 'F',
    //         label: '按钮',
    //     }
    // ];

    const columns =[
        {
            title: '菜单名称',
            dataIndex: 'menuName',
            key: 'menuName',
        },
        {
            title: '菜单图标',
            dataIndex: 'icon',
            key: 'icon',
            render: (text, record) => {
                return <SvgIcon iconName={record.icon} />
            }
        },
        {
            title: '菜单排序',
            dataIndex: 'orderNum',
            key: 'orderNum',
        },
        {
            title: '权限标识',
            dataIndex: 'perms',
            key: 'perms',
        },
        {
            title: '组件路径',
            dataIndex: 'component',
            key: 'component',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text, record) => {
                return (<DictTag dictType="sys_normal_disable" value={text} options={sys_normal_disable} ></DictTag>)
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => 
                <Space size="middle">
                <Button type='link' onClick={() => handleAdd(record)}>新增</Button>
                <Button type='link' onClick={() => handleUpdate(record)}>修改</Button>
                <Popconfirm
                title="删除确认"
                description={`是否确认删除用户编号为 ${record.menuId} 的数据项？`}
                onConfirm={() => handleDelete(record)}
                onCancel={delCancel}
                okText="确定"
                cancelText="取消"
                >
                <Button type='link'>删除</Button>
                </Popconfirm>
                </Space>
        }
        
    ];
    useEffect(() => {
        getListMenu();
    }, [queryParams]);

    const getListMenu = async () => {
        const res = await listMenu(queryParams);
        //console.log(res);
        const treeData = handleTree(res.data,'menuId');
        console.log(treeData);
        setMenuList(treeData);

    }

    const handleAdd = (record) => {
        console.log('新增');
        formAdd.resetFields();
        setTitle('新增菜单');
        setOpen(true);
        getTreeselect();
        formAdd.setFieldValue('menuType','M')
        if(record.menuId !== undefined) {
            formAdd.setFieldValue('parentId',record.menuId)
        }
    }
    const handleUpdate = (record) => {
        const menuId = record.menuId;
        formAdd.resetFields();
        getTreeselect();
        getMenu(menuId).then(res => {
            formAdd.setFieldsValue(res.data);
            console.log(formAdd.getFieldsValue());
        })
        setTitle('修改菜单');
        setOpen(true);
        
    }

    const handleDelete = (record) => {
        console.log(record);
        delMenu(record.menuId).then(res => {
            if(res.code === 200) {
                message.success('删除成功');
                getListMenu();
            } else {
                message.error(res.msg);
            }
        })
    }

    const delCancel = () => {
        message.error('取消删除');
    }

    const handleOk = () => {
        console.log('===========handleOk==========',formAdd.getFieldValue());
        setOpen(false);
        if(formAdd.getFieldValue().menuId === undefined) {
        addMenu(formAdd.getFieldValue()).then(res => {
            console.log(res);
            if(res.code === 200) {
                message.success('添加成功');
                getListMenu();
            } else {
                message.error(res.msg);
            }
        })
    } else {
        updateMenu(formAdd.getFieldValue()).then(res => {
            console.log(res);
            if(res.code === 200) {
                message.success('修改成功');
                getListMenu();
            } else {
                message.error(res.msg);
            }
        })
    }

    }
    const handleCancel = () => {
        setOpen(false);
        console.log('cancel');
    }

     /** 查询菜单下拉树结构 */
 function getTreeselect() {
    setMenuOptions([]);
    listMenu().then(response => {
      const menu = { menuId: 0, menuName: "主类目", children: [] };
      menu.children = handleTree(response.data, "menuId");
      setMenuOptions([menu]);
    });
  }

  // 定义一个函数，当图标选择改变时调用
  // 定义一个函数，当图标选择改变时调用
    // 打印出选择的图标值
  const onIconSelectChange = (value) => {
    //console.log(value);
  }

  const onMenuTypeChange = (e) => {
    //console.log('======onMenuTypeChange======',e.target.value);
    setMenuType(e.target.value);
  }

  const onFinish = (values) => {
    console.log('Success:', values);
    setQueryParams(values);
  }

  return (
    <div>
        <Row gutter={[16, 16]} style={{marginBottom: '20px'}}>
            <Col span={24}>
            <Form form={searchForm} layout="inline" onFinish={onFinish}>
                <Form.Item label="菜单名称" name="menuName">
                    <Input placeholder="请输入菜单名称" allowClear/>
                </Form.Item>
                <Form.Item label="状态" name="status" style={{width: '10%'}}> 
                    <Select placeholder="请选择状态" options={sys_normal_disable.value}  allowClear/>
                </Form.Item>
                <Form.Item>
                    <Space>
                    <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>搜索</Button>
                    <Button type="default" icon={<RedoOutlined />} onClick={() => searchForm.resetFields()}>重置</Button>
                    </Space>
                </Form.Item>
            </Form>
            </Col>
        </Row>
        <Row gutter={[16, 16]}>
            <Col span={24}>
            <Space>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增</Button>
          </Space>
            </Col>
        </Row>
        <Row gutter={[16, 16]}>
            <Col span={24}>
            <Table columns={columns} dataSource={menuList} pagination={false} rowKey={(record) => record.menuId}  scroll={{y: 500 }}/>
            </Col>
        </Row>
        <Modal title={title} open={open} onOk={handleOk} onCancel={handleCancel} width={600} >
            <Form form={formAdd} layout="inline" style={{marginTop: '20px'}}>
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                <Col span={24}>
                <Form.Item label="上级菜单" name="parentId" style={{width: '100%'}}>
                    <TreeSelect
                        showSearch
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        fieldNames={{ label: 'menuName', value: 'menuId', children: 'children' }} 
                        placeholder="请选择上级菜单"
                        allowClear
                        treeDefaultExpandAll
                        treeData={menuOptions}
                    />
                </Form.Item>
                </Col>
                </Row>
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    <Col span={24}>
                <Form.Item label="菜单类型" name="menuType" >
                    <Radio.Group onChange={onMenuTypeChange}>
                        <Radio value="M">目录</Radio>
                        <Radio value="C">菜单</Radio>
                        <Radio value="F">按钮</Radio>
                    </Radio.Group>
                </Form.Item>
                </Col>
                </Row>
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                <Col span={24}>
                <Form.Item label="菜单图标" name="icon" style={{width: '100%'}}>
                    <IconSelect onChange={onIconSelectChange}/>
                </Form.Item>
                </Col>
                </Row>
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    <Col span={12}>
                <Form.Item label="菜单名称" name="menuName">
                    <Input />
                </Form.Item>
                </Col>
                <Col span={12}>
                <Form.Item label="菜单排序" name="orderNum">
                    <InputNumber />
                </Form.Item>
                </Col>
                </Row>
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    <Col span={12}>
                <Form.Item label="是否外链" name="isFrame">
                    <Radio.Group>
                        <Radio value="0">是</Radio>
                        <Radio value="1">否</Radio>
                    </Radio.Group>
                </Form.Item>
                </Col>
                <Col span={12}>
                <Form.Item label="路由地址" name="path">
                    <Input />
                </Form.Item>
                </Col>
                </Row>
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    
                {menuType === 'C' && <>
                <Col span={12}>
                <Form.Item label="组件路径" name="component">
                    <Input />
                </Form.Item>
                </Col>
                </>}
                {menuType !== 'M' && <>
                    <Col span={12}>
                <Form.Item label="权限标识" name="perms">
                    <Input />
                </Form.Item>
                </Col>
                </>}
                </Row>
                {menuType === 'C' && <>
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                <Col span={12}>
                <Form.Item label="路由参数" name="query">
                    <Input />
                </Form.Item>
                </Col>
                    <Col span={12}>
                <Form.Item label="是否缓存" name="isCache">
                    <Radio.Group>
                        <Radio value="0">缓存</Radio>
                        <Radio value="1">不缓存</Radio>
                    </Radio.Group>
                </Form.Item>
                </Col>
                </Row>
                </>}
                <Row gutter={[16, 16]} style={{marginBottom: '20px', width: '100%'}}>
                    <Col span={12}>
                <Form.Item label="显示状态" name="visible">
                    <Radio.Group>
                        <Radio value="0">显示</Radio>
                        <Radio value="1">隐藏</Radio>
                    </Radio.Group>
                </Form.Item>
                </Col>
                <Col span={12}>
                <Form.Item label="菜单状态" name="status">
                    <Radio.Group>
                        <Radio value="0">正常</Radio>
                        <Radio value="1">停用</Radio>
                    </Radio.Group>
                </Form.Item>
                </Col>
                </Row>
            </Form>
        </Modal>
    </div>
  );
}

export default Menu;